<?php

namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use App\Models\PayMethod;

use App\Services\AgentPriceService;

class PayService
{
    //获取可用支付通道
    public function getPayMethod(){
        //获取支付方式
        $pay_method = Cache::rememberForever('pay_method',  function () {
            $method =  PayMethod::round()->show()->orderBy('sort')->with(['configs' => function ($query) {
                $query->where('state', 1)->limit(1);
            }])->first();
            $data['type'] = '';
            $data['config'] = [];
            if($method && count($method->configs)){
                $data['type'] = $method->slug;
                $data['config'] = $method->configs[0]->toArray();
            }
            return $data;
        });
        return $pay_method;
    }

    //获取内付通道
    public function getWechatPayMethod(){
        //获取支付方式
        $pay_method = Cache::rememberForever('pay_method_wechat',  function () {
            $method =  PayMethod::show()->orderBy('sort')->where('slug','wechat_official')->with(['configs' => function ($query) {
                $query->where('state', 1)->limit(1);
            }])->first();
            $data['type'] = '';
            $data['config'] = [];
            if($method && count($method->configs)){
                $data['type'] = $method->slug;
                $data['config'] = $method->configs[0]->toArray();
            }
            return $data;
        });
        return $pay_method;
    }
    //获取扫码通道
    public function getSmPayMethod(){
        //获取支付方式
        $pay_method = Cache::rememberForever('pay_method_sm',  function () {
            $method =  PayMethod::show()->orderBy('sort')->where('slug','sevenSm')->with(['configs' => function ($query) {
                $query->where('state', 1)->limit(1);
            }])->first();
            $data['type'] = '';
            $data['config'] = [];
            if($method && count($method->configs)){
                $data['type'] = $method->slug;
                $data['config'] = $method->configs[0]->toArray();
            }
            return $data;
        });
        return $pay_method;
    }
    // --------------------------------微信公众号支付  开始--------------------------------//
    //微信支付配置
    protected $wxPayConfig = [
        'app_id' => '', // 公众号 APPID
        'mch_id' => '',
        'key' => '',
        'notify_url' => '',
        'cert_client' => '', // optional，退款等情况时用到
        'cert_key' => '',// optional，退款等情况时用到
        'log' => [ // optional
            'file' => './logs/wechat_pay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'daily', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 10.0,
            'connect_timeout' => 10.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
    ];

    /**
     * 获取微信支付配置
     *
     * @return void
     */
    public function getWxPayConfig(){
        //获取支付方式
        $pay_method = $this->getWechatPayMethod();
        //支付
        if($pay_method['type'] && count($pay_method['config']) && $pay_method['type']=='wechat_official'){
            $config = $this->wxPayConfig;
            $config['app_id']= $pay_method['config']['appid'];
            $config['mch_id']= $pay_method['config']['mchid'];
            $config['key']= $pay_method['config']['key'];
            $config['log']['file']= storage_path('logs/wechat_pay.log');
            $config['log']['level']= config('app.debug')?'debug':'info';
            $config['notify_url']= "http://{$pay_method['config']['domain']}/wxpaynotify/";

            return $config;
        }
        else return [];
    }

    // --------------------------------微信公众号支付  结束--------------------------------//


    // --------------------------------七七扫码  开始--------------------------------//

    /**
     * 扫码下单
     */
    public function smCreateOrder($config,$money,$no,$born_domain,$attach=''){
        $domain = $config['domain'];
        $paydata = array (
            'mchId' => $config['mchid'],//"600500010", //商户ID，后台提取
            'billNo' => $no,//time ().mt_rand(1111,9999), //商户订单号
            'totalAmount' => bcmul(ceil($money),100), //金额
            'billDesc' => "在线充值", //商品名称
            'way' => 'qrcode', //支付模式 二维码qrcode h5 wap
            'payment' => 'wechat', //微信支付
            'notifyUrl' => 'http://'.$born_domain.'/pay/7-sm-notify', //回调地址 
            'returnUrl' => 'http://'.$born_domain.'/pay/7-success?no='.$no, //同步跳转 
            'attach' => $attach,
            "accKey" => $config['appid'] //收款账号，如果需要指定充值帐号请传此值否则为轮询
        );
        $Md5key = $config['key']; //签名密钥，后台提取
        $paydata ['sign'] = self::markSign ( $paydata, $Md5key );
        $payUrl = "http://$domain/game/unifiedorder"; //请求订单地址
        $checkUrl = "http://$domain/pay/checkOrder"; //主动查单地址
        $ret = self::curl ( $payUrl, json_encode ( $paydata ) );
        $data = json_decode ( $ret, true );
        if ($data ['code'] == 0) {
            $data ['result']["totalAmount"] = $paydata["totalAmount"]/100;
            $data ['result']["returnUrl"] = $paydata["returnUrl"];
            $data ['result']["checkUrl"] = $checkUrl;
            $data ['result']["checksign"] = md5($data ['result']['tradeNo'].'checkG1#s12s2');
            if ($paydata['way'] == "qrcode"){
                // $url="/p/7-qrcode"; //二维码付款页面
                // $data['url'] = $url;
                return $data;
                // jumpPost($url,$data ['result']);
            } else {
                $url="html/h5.php"; //h5付款页面
                jumpPost($url,$data ['result']);
            }
        } else {
           return $data;
            // exit ( $data ['message'] );
        }
    }
    /**
     * 请求方法
     */
    function curl($url, $post_data) {
        $ch = curl_init ();
        $header = [
                'Content-Type: application/json',
                'Content-Length: ' . strlen ( $post_data )
        ];
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        $output = curl_exec ( $ch );
        curl_close ( $ch );
        return $output;
    }

    /**
     * 签名方法
     */
    function markSign($paydata, $signkey) {
        ksort ( $paydata );
        $str = '';
        foreach ( $paydata as $k => $v ) {
            if ($k != "sign" && $v != "") {
                $str .= $k . "=" . $v . "&";
            }
        }
        return strtoupper ( md5 ( $str . "key=" . $signkey ) );
    }
    // --------------------------------七七扫码  结束--------------------------------//
    

    // -------------------------------- 和珅支付 --------------------------------//
    /**
     * 下单
     */
    public function hsCreateOrder($config,$money,$no){
         //获取落地
        $born_domain = cache()->rememberForever('born_domain',  function () {
            //落地有可能没有了，所以加锁防止没有时缓存穿透
            return cache()->lock('born_domain')->get(function () {
                // 获取无限期锁并自动释放...
                return Domain::show()->born()->orderBy('sort')->value('domain');
            });
        });

        $pay_domain = $config['domain'];
        $key = $config['key'];
        $titles = config('visit.paytitles');
        $title = $titles[array_rand($titles)];
        $paydata = array (
            'key' => $key,
            'pid' => $config['mchid'], //商户ID，后台提取
            'out_trade_no' => $no,//商户订单号
            'money' => $money, //金额
            'name' => $title, //商品名称
            'type' => 'wxpay', 
            'notify_url' => 'http://'.$born_domain.'/pay/hs-notify', //服务器异步通知地址
            'return_url' => 'http://'.$born_domain.'/pay/hs-success', //页面跳转通知地址
            'sign_type'=>'MD5',
        );
        $param = self::createLinkstring(self::argSort(self::paraFilter($paydata)));
        $sign= self::md5Sign($param, $key);
        $payUrl = "http://$pay_domain/submit.php"; //请求订单地址
        $url = "{$payUrl}?{$param}&sign={$sign}";
        return $url;
    }


    /**
	 * 生成签名
	 */
    function md5Sign($prestr, $key) {
        $prestr = $prestr . $key;
        return md5($prestr);
    }
    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param $para 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    function createLinkstring($para) {
        $arg  = "";
        foreach ($para as $key=>$val) {
            $arg.=$key."=".$val."&";
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,-1);
        
        return $arg;
    }
    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
     * @param $para 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    function createLinkstringUrlencode($para) {
        $arg  = "";
        foreach ($para as $key=>$val) {
            $arg.=$key."=".urlencode($val)."&";
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,-1);

        return $arg;
    }
    /**
     * 除去数组中的空值和签名参数
     * @param $para 签名参数组
     * return 去掉空值与签名参数后的新签名参数组
     */
    function paraFilter($para) {
        $para_filter = array();
        foreach ($para as $key=>$val) {
            if($key == "sign" || $key == "sign_type" || $val == "")continue;
            else $para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }
    /**
     * 对数组排序
     * @param $para 排序前的数组
     * return 排序后的数组
     */
    function argSort($para) {
        ksort($para);
        reset($para);
        return $para;
    }

    // -------------------------------- 和珅支付  结束--------------------------------//
}
